#!/usr/bin/env python
# encoding: utf-8
"""
@Author : Kylin
@Email : dongsai0520@gmail.com
@Time : 2022/12/14 12:53 
@Version : v1.0.0
@Remark : ***
"""

from appium import webdriver
import time
import yaml
import os

import xlrd
import math


# from tomorrow import threads

# from src.pages import login_page
# from config.globalparameter import login_name, login_password, yaml_path


def start_appium(port, bootstrap,udid):
    commond = f"appium -a 127.0.0.1 -p {port} --session-override -bp {bootstrap} -U {udid} "
    os.system(commond)

def stop_appium():  # 关闭所有的appium进程
    os.system("start /b taskkill /F /t /IM node.exe")


def get_desired_caps(devices_name):
    """
    从yaml读取desired_caps配置信息
    参数name:设备名称,如：夜神/真机1
    :return: desired_caps字典格式

    """
    # curpath = os.path.dirname(os.path.realpath(__file__))
    yamlpath = os.path.join("./", "yaml_appium.yaml")
    print("配置地址：%s" % yamlpath)
    f = open(yamlpath, "r", encoding="utf-8")
    a = f.read()
    f.close()
    # 把yaml文件转字典
    d = yaml.safe_load(a)
    for ii in d:
        if devices_name in ii["desc"]:  # 判断输入的设备名称是否存在
            # print(ii)
            # 启动服务
            devicesname = ii['desired_caps']['udid']
            print("devicesName: %s" % devicesname)
            # print("port: %s" %ii[\'port\'])
            # start_appium(port=ii['port'], bootstrap=ii['bootstrap-port'], udid=ii['desired_caps']['udid'])
            start_appium(port=ii['port'], bootstrap=ii['bootstrap-port'], udid=ii['desired_caps']['udid'])
            # start_appium(port=ii[\'port\'], udid=devicesName)
            # package_name = get_package_name()
            # ii['desired_caps']['appPackage'] = package_name
            return ii['desired_caps'], ii['port']

def run_app(devices_name):
    # 配置参数
    desired_caps = get_desired_caps(devices_name)
    print(desired_caps)
    #print(desired_caps[1])
    # 执行代码
    # driver = webdriver.Remote('http://127.0.0.1:%s/wd/hub' % desired_caps[1], desired_caps[0])
    # time.sleep(5)
    # login_page1 = login_page.login_page(driver)
    # login_page1.input_user(login_name)
    # login_page1.input_Pws(login_password)
    # login_page1.click_btnLogin()
    # self.driver.find_element_by_id(\'com.zhijiepay.android:id/but_OK\').click()
    # 设置隐式等待时间
    # driver.implicitly_wait(3)
    # time.sleep(5)


if __name__ == "__main__":
    devices = ["b62090bf"]
    for i in devices:
        run_app(devices_name=i)
